package com.ig.amazon.service;

import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import com.amazonaws.a2s.AmazonA2SClient;
import com.amazonaws.a2s.model.Condition;
import com.amazonaws.a2s.model.Item;
import com.amazonaws.a2s.model.ItemAttributes;
import com.amazonaws.a2s.model.ItemLookupRequest;
import com.amazonaws.a2s.model.ItemLookupResponse;
import com.amazonaws.a2s.model.ItemSearchRequest;
import com.amazonaws.a2s.model.ItemSearchResponse;
import com.amazonaws.a2s.model.Items;
import com.ig.model.Search;

public class AmazonServiceUtil implements AmazonServiceConstants {
	private static AmazonA2SClient amazonA2SClient;

	private static String awsAccessKeyId = null;

	private static String awsSubscriptionId = null;

	private static ResourceBundle rb;
	static {
		rb = ResourceBundle.getBundle(DB_PROPERTIES_FILE);
	}

	/**
	 * Retrieves info about the specified product.
	 * 
	 * @param idType
	 *            The type of ID(s) being used - from AmazonA2SIdType.
	 * @param idList
	 *            The IDs of the items to lookup.
	 * @param searchIndex
	 *            The domain of the item to lookup - from AmazonA2SSearchIndex.
	 * @param responseGroups
	 *            The list of response groups to return - from
	 *            AmazonA2SResponseGroup.
	 */
	public static ItemLookupResponse retrieveItemsInfo(String idType,
			String id, String searchIndex, List<String> responseGroups)
			throws Exception {

		// Ensure that client distribution is configured
		setupAmazonA2SClient();
		ItemLookupRequest request = new ItemLookupRequest();
		request.setIdType(idType);
		request.setItemId(makeSingleTypedList(id));
		// request.setCondition(Condition.ALL);
		request.setSearchIndex(searchIndex);
		// request.setMerchantId("All");
		request.setResponseGroup(responseGroups);
		return amazonA2SClient.itemLookup(request);
	}

	/**
	 * Retrieves info about the specified product from Amazon.
	 * 
	 * @param Search -
	 *            Search Criteria Bean
	 */
	public static ItemSearchResponse retrieveAmazonsResponse(
			Search searchCriteria) throws Exception {

		// Ensure that client distribution is configured
		setupAmazonA2SClient();
		ItemSearchRequest request = new ItemSearchRequest();
		request
				.setCondition(Condition
						.fromValue(searchCriteria.getCondition()));
		request.setSearchIndex(searchCriteria.getSearchIndex());
		request.setMinimumPrice(searchCriteria.getMinPrice());
		request.setMaximumPrice(searchCriteria.getMaxPrice());
		request.setKeywords(searchCriteria.getKeyWords());
		request.setResponseGroup(searchCriteria.getResponseGroups());
		return amazonA2SClient.itemSearch(request);
	}

	public static Items getItems(ItemLookupResponse response) throws Exception {

		List<Items> itemsList = response.getItems();
		if (itemsList.size() != 1)
			throw new Exception("Unexpected items count");

		return itemsList.get(0);
	}

	public static List<Items> getItems(ItemSearchResponse response)
			throws Exception {
		return response.getItems();
	}

	public static Item getItemByProductCode(ItemLookupResponse response,
			boolean is_book, String product_code) throws Exception {

		Items items = getItems(response);

		int count = items.getItem().size();

		for (Item item : items.getItem()) {

			ItemAttributes attribute = item.getItemAttributes();
			if (attribute == null)
				throw new Exception("Results must contain ItemAttributes group");

			if (count == 1) {
				return item;
			} else {
				if (is_book) {
					if (attribute.getEAN().equalsIgnoreCase(product_code))
						return item;
				} else {
					if (attribute.getUPC().equalsIgnoreCase(product_code))
						return item;
				}
			}
		}

		return null;
	}

	/** creates Amazon service client based on key and subscription Id */
	public static synchronized void setupAmazonA2SClient() throws Exception {
		awsAccessKeyId = (awsAccessKeyId != null) ? awsAccessKeyId
				: getProperty(AWS_ACCESS_KEY_ID);
		awsSubscriptionId = (awsSubscriptionId != null) ? awsSubscriptionId
				: getProperty(AWS_SUBSCRIPTTION_ID);
		amazonA2SClient = new AmazonA2SClient(awsAccessKeyId, awsSubscriptionId);
	}

	public static String getProperty(String str) {
		return rb.getString(str);
	}

	/** Builds a list containing the single typed object specified. */
	public static <Type> List<Type> makeSingleTypedList(Type object) {
		List<Type> list = new ArrayList<Type>();
		list.add(object);
		return list;
	}
}
